﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.CustomerService.Controllers
{
    public class ServiceProviderWorkOrderController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        #region 获取报案工单任务列表数据
        /// <summary>
        /// 获取报案工单任务列表数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Index(InsuranceWarrantyRecordModel model)
        {
            var total = 0;
            var list = ServiceFactory.InsuranceWarrantyRecordServiceInstance.GetPagingList(model, out total).Include(o => o.SystemUser).Include(o => o.InsuranceOrder).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.InsuranceOrderId,
                o.WarrantyRecordNo,
                o.Reporter,
                o.ReporterPhone,
                o.Status,
                StatusDesc = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance.GetStatusName(o.Status),
                o.CreateTime,
                o.LastModifyTime,
                o.InsuranceOrder.InsuranceCompany,
                o.InsuranceOrder.InsuranceCompanyBranch,
                o.ServiceProviderBranch.ServiceProvider.ServiceProviderName,
                AccessoriesType = "维修配件",
                WarrantyMaintenanceType = EnumHelper.Instance.GetDescription(typeof(WarrantyMaintenanceType), o.WarrantyMaintenanceTypeID),
                o.SortingCenterSendOrderUserID,
                SendOrderTime = o.SendOrderTime.HasValue ? o.SendOrderTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",

            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion
        public ActionResult Detail(int id)
        {
            var insuranceWarrantyRecord = ServiceFactory.InsuranceWarrantyRecordServiceInstance.LoadByID(id);
            return View(insuranceWarrantyRecord);
        }
        public ActionResult FeedbackIssue(InsuranceWarrantyRecordFeedBackIusses model)
        {
            if (model.ID > 0)
                model = ServiceFactory.InsuranceWarrantyRecordFeedBackIussesServiceInstance.Load(model.ID);
            return View(model);
        }

        #region 维修完成

        [HttpPost]
        [ValidateInput(true)]
        public ActionResult SaveCompleteMaintainInsuranceWarrantyRecord(InsuranceWarrantyRecord model, InsuranceWarrantyRecordExpressInfo insuranceWarrantyRecordExpressInfo, IList<InsuranceWarrantyRecordAuditInfo> insuranceWarrantyRecordAuditInfo, List<InsuranceWarrantyRecordAccessories> insuranceWarrantyRecordAccessories, int saveType)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Save
            };

            var warrantyRecordService = ServiceFactory.InsuranceWarrantyRecordServiceInstance;
            var auditInfoService = ServiceFactory.InsuranceWarrantyRecordAuditInfoServiceInstance;

            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    var entity = warrantyRecordService.LoadByID(model.ID);
                    entity.WithTheMachineAccessories = model.WithTheMachineAccessories;//随机附件
                    entity.ServiceProviderReceiveMachineTime = model.ServiceProviderReceiveMachineTime;//接机时间
                    entity.RepairEngineerUser = model.RepairEngineerUser;//维修工程师
                    if (saveType == 2)
                    {
                        entity.Status = (byte)InsuranceWarrantyStatus.Close;
                        entity.LastModifyBy = CurrentUser.UserAccount;
                        entity.LastModifyTime = DateTime.Now;
                        if (model.Status != entity.Status)
                        {
                            //获取父级状态
                            var service = ServiceFactory.InsuranceWarrantyRecordStatusServiceInstance;
                            InsuranceWarrantyRecordStatus newStatusInfo = service.LoadEntities(t => t.StatusCode == entity.Status).FirstOrDefault();

                            //记录流程日志
                            InsuranceWarrantyRecordStatus oldStatusInfo = service.LoadEntities(t => t.StatusCode == model.Status).FirstOrDefault();
                            var insuranceWarrantyRecordController = new InsuranceWarrantyRecordController();
                            insuranceWarrantyRecordController.WriteProcessLog(oldStatusInfo, newStatusInfo, null, model.ID);
                        }
                        responseResult.Success = warrantyRecordService.UpdateEntities(entity);
                    }
                    if (saveType == 1 || responseResult.Success)
                    {
                        if (insuranceWarrantyRecordAuditInfo != null && insuranceWarrantyRecordAuditInfo.Any())//保存审核信息
                            responseResult.Success = auditInfoService.Save(model.ID, insuranceWarrantyRecordAuditInfo,
                                CurrentUser.UserAccount);
                        if (insuranceWarrantyRecordAccessories != null && insuranceWarrantyRecordAccessories.Any()) //保存维修详情
                        {
                            insuranceWarrantyRecordAccessories.ForEach(o => o.InsuranceWarrantyRecordID = model.ID);
                            responseResult.Success =
                                ServiceFactory.InsuranceWarrantyRecordAccessoriesServiceInstance.Save(
                                    insuranceWarrantyRecordAccessories, CurrentUser.UserAccount);
                        }
                    }
                    if (responseResult.Success)
                    {
                        var expressInfoService = ServiceFactory.InsuranceWarrantyRecordExpressInfoServiceInstance;
                        var expressInfoEntity = expressInfoService.Load(model.ID,
                            (byte)ExpressSendByWhoType.RepairCenterSendToUser);
                        if (expressInfoEntity != null)
                        {
                            expressInfoEntity.ExpressSendByWhoType = (byte)ExpressSendByWhoType.RepairCenterSendToUser;
                            expressInfoEntity.ExpressCompanyID = insuranceWarrantyRecordExpressInfo.ExpressCompanyID;
                            expressInfoEntity.ExpressNo = insuranceWarrantyRecordExpressInfo.ExpressNo ?? "";
                            expressInfoEntity.ExpressStatus = insuranceWarrantyRecordExpressInfo.ExpressStatus;
                            expressInfoEntity.SendUserPhone = insuranceWarrantyRecordExpressInfo.SendUserPhone ?? "";
                            expressInfoEntity.SendUserName = insuranceWarrantyRecordExpressInfo.SendUserName ?? "";
                            expressInfoEntity.SendUserAddress = insuranceWarrantyRecordExpressInfo.SendUserAddress;
                            expressInfoEntity.ExpressPrice = insuranceWarrantyRecordExpressInfo.ExpressPrice;
                            expressInfoEntity.ReceiverUserPhone = insuranceWarrantyRecordExpressInfo.ReceiverUserPhone ?? "";
                            expressInfoEntity.ReceiverUserName = insuranceWarrantyRecordExpressInfo.ReceiverUserName ?? "";
                            expressInfoEntity.ReceiverUserAddress = insuranceWarrantyRecordExpressInfo.ReceiverUserAddress ?? "";
                            expressInfoEntity.PickUpExpressManName = insuranceWarrantyRecordExpressInfo.PickUpExpressManName;
                            expressInfoEntity.PickUpExpressManPhone = insuranceWarrantyRecordExpressInfo.PickUpExpressManPhone;
                            responseResult.Success = expressInfoService.UpdateEntities(expressInfoEntity);
                        }
                        else
                        {
                            insuranceWarrantyRecordExpressInfo.ID = 0;
                            insuranceWarrantyRecordExpressInfo.ExpressSendByWhoType = (byte)ExpressSendByWhoType.RepairCenterSendToUser;
                            insuranceWarrantyRecordExpressInfo.InsuranceWarrantyRecordID = model.ID;
                            insuranceWarrantyRecordExpressInfo.CreatedBy = CurrentUser.UserAccount;
                            insuranceWarrantyRecordExpressInfo.CreatedTime = DateTime.Now;
                            responseResult.Success = expressInfoService.AddEntities(insuranceWarrantyRecordExpressInfo).ID > 0;
                        }
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    ts.Dispose();
                }
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        #endregion

        public ActionResult SaveFeedbackIssue(InsuranceWarrantyRecordFeedBackIusses model)
        {
            var responseResult = new ResponseResult { OpreateType = OpreateType.Save };
            var files = Request.Files;
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {

                    if (model.ID > 0)
                    {
                        var entity = ServiceFactory.InsuranceWarrantyRecordFeedBackIussesServiceInstance.Load(model.ID);
                        if (entity != null)
                        {
                            entity.IssueDesc = model.IssueDesc;
                            responseResult.Success = ServiceFactory.InsuranceWarrantyRecordFeedBackIussesServiceInstance.UpdateEntities(entity);
                        }
                    }
                    else
                    {
                        model.CreatedBy = CurrentUser.UserAccount;
                        model.CreatedTime = DateTime.Now;
                        model.Status = (byte)FeedbackIssueStatus.WaitingFeedbackConsulting;
                        responseResult.Success =
                            ServiceFactory.InsuranceWarrantyRecordFeedBackIussesServiceInstance.AddEntities(model).ID > 0;
                    }
                    if (responseResult.Success)
                    {
                        for (int i = 0; i < files.Count; i++)
                        {
                            var file = files[i];
                            var filePath = FileHelper.UploadFile(file, Server);
                            if (file != null && !string.IsNullOrEmpty(filePath))
                            {
                                var uploadFile = new UploadFiles
                                {
                                    CreateBy = CurrentUser.CreateBy,
                                    CreateTime = DateTime.Now,
                                    FilePath = filePath,
                                    FileSize = file.ContentLength,
                                    FileName = FileHelper.GetFileNameNoExtension(filePath),
                                    FileBelongTableName = NeedUploadFileDataTableEnums.InsuranceWarrantyRecordFeedBackIusses.ToString(),
                                    FileBelongTablePKID = model.ID
                                };
                                responseResult.Success =
                                    ServiceFactory.UploadFilesServiceInstance.AddEntities(uploadFile).ID > 0;
                            }
                        }
                    }
                    if (responseResult.Success)
                    {
                        ts.Complete();
                    }
                    else
                    {
                        ts.Dispose();
                    }
                }
                catch (Exception e)
                {
                    responseResult.Message = e.ToString();
                    ts.Dispose();
                }
            }

            TempData["responseResult"] = responseResult;
            return RedirectToAction("FeedbackIssue", new { insuranceWarrantyRecordID = model.InsuranceWarrantyRecordID });
        }
    }
}